package itbour.onetouchshow.widget.inching;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.RelativeLayout;

import itbour.onetouchshow.R;
import itbour.onetouchshow.bean.canvas.CompoundPathsBean;
import itbour.onetouchshow.bean.inching.noppt.InchingOutLineAllTypeV10Bean;
import itbour.onetouchshow.bean.inching.noppt.InchingOutLineImgBean;
import itbour.onetouchshow.utils.CommonUtils;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.UIUtils;


/**
 * Created by zjl_d on 2016/12/15.
 * 这是控制边框的控件
 */
public class NewInchingFrontBoderView extends View {
    public int mControllerWidth;
    public int mControllerHeight;
    //当该控件移动时 刷新当前选中的控件
    protected InchingOperaRelativeLayout nowSelectView;
    protected int nowPageIndex;
    protected int lastX;
    protected int lastY;
    protected InchingBaseAreaRelativeLayout rlInchingBaseArea;
    protected int moveX;
    protected int moveY;
    protected boolean inController;
    protected long currentMS;
    private Paint paint;
    private Paint textPaint;
    private Bitmap mControllerBitmap;
    private float DownX;
    private float DownY;

    public NewInchingFrontBoderView(Context context) {
        this(context, null);
    }

    public NewInchingFrontBoderView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public NewInchingFrontBoderView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initControllBitmap();
        initPaint();

    }

    public InchingOperaRelativeLayout getNowSelectView() {
        return nowSelectView;
    }

    public void setNowSelectView(InchingOperaRelativeLayout nowSelectView) {
        this.nowSelectView = nowSelectView;
    }

    private void initControllBitmap() {
        //设置控制点的图标
        mControllerBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.iv_inching_control);
        mControllerWidth = mControllerBitmap.getWidth();
        mControllerHeight = mControllerBitmap.getHeight();
    }

    private void initPaint() {

        paint = new Paint();
        paint.setColor(Color.parseColor("#16D3CD")); //设置画笔颜色
        paint.setStrokeWidth(UIUtils.dp2px(1));//设置画笔宽度
        paint.setStyle(Paint.Style.STROKE);
        paint.setAntiAlias(true);

        textPaint = new Paint();
        textPaint.setColor(Color.parseColor("#f57c1f"));
        textPaint.setStrokeWidth(1);//设置画笔宽度
        textPaint.setStyle(Paint.Style.FILL);
        textPaint.setAntiAlias(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //为了兼容 图片的外边框 丢一个假的进来
        Path path = new Path();

        int helf_controll_width = mControllerWidth / 2;
        int helf_controll_height = mControllerHeight / 2;
        //

        int canvasH = canvas.getHeight() - helf_controll_height;
        int canvasW = canvas.getWidth() - helf_controll_width;
        int broadWidth = (int) Math.ceil(UIUtils.dp2px(1) / 2.0);
        L_.i("canvasW===" + canvasW + "canvasH===" + canvasH +
                "canvas.getHeight===" + canvas.getHeight()
                + "canvas.getWidth===" + canvas.getWidth() + "broadWidth===" + broadWidth);
        path.moveTo(broadWidth, broadWidth);
        path.lineTo(broadWidth, canvasH);
        path.lineTo(canvasW, canvasH);
        path.lineTo(canvasW, broadWidth);
        path.close();

        canvas.drawPath(path, paint);
        canvas.drawBitmap(mControllerBitmap, canvas.getWidth() - mControllerWidth
                , canvas.getHeight() - mControllerHeight, textPaint);

        canvas.save();
        canvas.restore();

    }

    /**
     * 刷新边框控件
     *
     * @param w
     * @param h
     */
    public void refreshFontBoderView(int x, int y, float w, float h) {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) this.getLayoutParams();
        layoutParams.width = (int) Math.ceil(w + mControllerWidth / 2);
        layoutParams.height = (int) Math.ceil(h + mControllerHeight / 2);

        this.setLayoutParams(layoutParams);
        setVisibility(View.VISIBLE);

        postInvalidate();
    }

    /**
     * 刷新边框控件
     */
    public void refreshFontBoderView(int x, int y) {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) this.getLayoutParams();

        layoutParams.leftMargin = x;
        layoutParams.topMargin = y;

        this.setLayoutParams(layoutParams);
        setVisibility(View.VISIBLE);

        postInvalidate();
    }

    /**
     * 刷新边框控件
     *
     * @param w
     * @param h
     */
    public void refreshFontBoderView(float w, float h) {
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) this.getLayoutParams();
        layoutParams.width = (int) Math.ceil(w + mControllerWidth / 2);
        layoutParams.height = (int) Math.ceil(h + mControllerHeight / 2);

        this.setLayoutParams(layoutParams);
        setVisibility(View.VISIBLE);

        postInvalidate();
    }

    //
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        getParent().requestDisallowInterceptTouchEvent(true);

        if (nowSelectView != null) {
            if (nowSelectView.touchEventListener != null) {
                nowSelectView.touchEventListener.onTouchEvent(event);
            }
        }

        int ea = event.getAction();

        if (ea == MotionEvent.ACTION_DOWN) {
            actionDown(event);
            currentMS = System.currentTimeMillis();//long currentMS     获取系统时间
            jugleActionDownIsInControl(event);
            L_.i("MotionEvent.ACTION_DOWN");
        } else if (ea == MotionEvent.ACTION_MOVE) {
            getNowSelectView().setThisDottedLineIsShow(0);
            actionMove(event);

            int[] locationMove = new int[2];
            getLocationOnScreen(locationMove);//获取在整个屏幕内的绝对坐标
            int viewInWindowsX = locationMove[0];
            int viewInWindowsY = locationMove[1];
            if (inController) {

                //如果在控制点中 变换边框的位置
                L_.i("inController");
                float newW = event.getRawX() - viewInWindowsX;
                float newH = event.getRawY() - viewInWindowsY;

                //最小的宽高
                int minWH = UIUtils.dp2px(10);
                int maxW = rlInchingBaseArea.getMaxW() - ((int) nowSelectView.getX());
                int maxH = rlInchingBaseArea.getMaxH() - ((int) nowSelectView.getY());
                L_.i("ACTION_MOVEgetX===" + getX() + "getY===" + getY() + "maxW===" + maxW + "maxH===" + maxH);

                newW = newW < minWH ? minWH : newW;
                newH = newH < minWH ? minWH : newH;

                //计算最大的宽高
                newW = newW > maxW ? maxW : newW;
                newH = newH > maxH ? maxH : newH;
                L_.i("newW===" + newW + "newH===" + newH + "getWidth===" + getWidth() + "getHeight===" + getHeight());
                //刷新边框控件
                //抬手的时候再更新 如果控制点拉出的宽高大于当前宽高 同时放大容器
                //如果控制点拉出的宽高小于当前宽高 只更新边框 不刷新容器

                InchingOutLineAllTypeV10Bean allTypeData = nowSelectView.getData();


                nowSelectView.inControlMoveThisView((int) Math.ceil(maxW + mControllerWidth / 2), (int) Math.ceil(maxH + mControllerHeight / 2));
                refreshFontBoderView(newW, newH);


                if (allTypeData instanceof InchingOutLineImgBean) {
                    InchingOutLineImgBean data = (InchingOutLineImgBean) allTypeData;
                    CompoundPathsBean compoundPathsBean = data.getMask().get(0);

                    InchingOperaRelativeLayout nowSelectView = getNowSelectView();
                    InchingOpreaImageView img = nowSelectView.findViewById(R.id.inching_can_opear_img);


                    //计算path的对于当前可见控件的缩放比及其偏移量
                    float wMask = compoundPathsBean.getW();
                    float hMask = compoundPathsBean.getH();


                    float maskScaleW = newW * 1.0f / wMask;
                    float maskScaleH = newH * 1.0f / hMask;


                    float maskX = 0.5f * (img.getWidth() - wMask * maskScaleW);
                    float maskY = 0.5f * (img.getHeight() - hMask * maskScaleH);

                    Path path = CommonUtils.getOnControlMoveScalePath(compoundPathsBean, maskScaleW, maskScaleH, maskX, maskY);


                    int thisInchingImageWidth = img.getWidth();
                    int thisInchingImageHeight = img.getHeight();

                    float sw = newW * 1.0f / thisInchingImageWidth;
                    float sh = newH * 1.0f / thisInchingImageHeight;
                    float scale = sw > sh ? sw : sh;

                    float ivW = scale * thisInchingImageWidth;
                    float ivh = scale * thisInchingImageHeight;
                    float ivX = 0.5f * (newW - ivW);
                    float ivY = 0.5f * (newH - ivh);

                    L_.i("图片测试===ivX===" + ivX + "ivY===" + ivY
                            + "ivW===" + ivW + "ivH===" + ivh + "scale==="
                            + scale + "newW===" + newW + "newH===" + newH);

                    img.refreshInchingImageViewMask(ivX, ivY);
                    img.setOnMaskChange(true, path, ivW, ivh);
                    img.setNeedClip(false);

                }

            } else {
                //如果不在控制点中 移动该控件
                L_.i("uninController");

                int dx = (int) event.getRawX() - lastX;
                int dy = (int) event.getRawY() - lastY;

                int l = nowSelectView.getLeft() + dx;
                int b = nowSelectView.getBottom() + dy;
                int r = nowSelectView.getRight() + dx;
                int t = nowSelectView.getTop() + dy;

                int minX = rlInchingBaseArea.getlB();
                int minY = rlInchingBaseArea.gettB();
                int maxX = rlInchingBaseArea.getrB();
                int maxY = rlInchingBaseArea.getbB();
                L_.i("newMove===minX" + minX + "minY===" + minY + "maxX===" + maxX + "maxY===" + maxY);
                //移动时计算边界
                if (l < minX) {
                    l = minX;
                    r = l + getWidth();
                }
                if (t < minY) {
                    t = minY;
                    b = t + getHeight();
                }

                if (r > maxX) {
                    r = maxX;
                    l = r - getWidth();
                }

                if (b > maxY) {
                    b = maxY;
                    t = b - getHeight();
                }

                lastX = (int) event.getRawX();
                lastY = (int) event.getRawY();

                nowSelectView.moveThisView(l, t);
                L_.i("newmovel===" + l + "t===" + t);

            }
            L_.i("MotionEvent.ACTION_MOVE");
        } else if (ea == MotionEvent.ACTION_UP) {
            //抬手时根据边框的宽高计算
            long moveTime = System.currentTimeMillis() - currentMS;//移动时间
            //认为移动了
            if ((moveTime > 20 && (Math.abs(moveX) > 2 || Math.abs(moveY) > 2))
                    || (inController && moveX == 0 && moveY == 0)) {
                //都是抬手后更新微调数据
                int x = (int) (nowSelectView.getX());
                int y = (int) (nowSelectView.getY());
                int w = getWidth() - rlInchingBaseArea.getCw() / 2;
                int h = getHeight() - rlInchingBaseArea.getCh() / 2;
                L_.i("更新数据upDateThisViewx===="
                        + x + "y===" + y + "w===" + w + "h===" + h + "getWidth===" + getWidth()
                        + "getHeight===" + getHeight() + nowPageIndex);

                //inController 是否是控制点控制
                nowSelectView.upDateThisView(inController, nowPageIndex, x, y, w, h, this);

                if (nowSelectView != null) {
                    if (nowSelectView.touchEventListener != null) {
                        nowSelectView.touchEventListener.onMoveOver(this, x, y);
                    }
                }
            } else {
                //执行点击事件
                performClick();
                L_.i("performClick()");

            }

        }
        return true;


    }

    /**
     * 用于判断是单击还是移动
     *
     * @param event
     */
    protected void actionMove(MotionEvent event) {
        moveX += (event.getRawX() - DownX);//X轴距离
        moveY += (event.getRawY() - DownY);//y轴距离
        L_.i("1actionMovemoveX===" + moveX + "moveY===" + moveY + "getX===" + event.getX() + "getY===" + event.getY() + "downX===" + DownX + "downY===" + DownY);
        DownX = event.getRawX();
        DownY = event.getRawY();
    }

    protected void actionDown(MotionEvent event) {
        currentMS = System.currentTimeMillis();//long currentMS     获取系统时间
        DownX = event.getRawX();//float DownX
        DownY = event.getRawY();//float DownY
        L_.i("1actionDownmoveX===" + moveX + "moveY===" + moveY + "getX===" + event.getX() + "getY===" + event.getY() + "downX===" + DownX + "downY===" + DownY);

        moveX = 0;
        moveY = 0;
    }

    /**
     * 判断当手指按下时 是否在控制点范围内
     *
     * @param event
     */
    public void jugleActionDownIsInControl(MotionEvent event) {
        lastX = (int) event.getRawX();// 获取触摸事件触摸位置的原始X坐标
        lastY = (int) event.getRawY();
        //判断是否在控制图标区域内
        //这里的px,py是当前右侧终点的坐标
        int[] location = new int[2];
        getLocationOnScreen(location);//获取在整个屏幕内的绝对坐标
        //再拿现在宽高
        int height = getHeight();
        int width = getWidth();

        int px = width + location[0];
        int py = (height + location[1]);

        inController = isInController(lastX, lastY, px, py);

    }

    /**
     * 判断当前触点 是否在控制区域内
     *
     * @param x
     * @param y
     * @param rx
     * @param ry
     * @return
     */
    private boolean isInController(float x, float y, float rx, float ry) {

        RectF rectF = new RectF(rx - mControllerWidth,
                ry - mControllerHeight,
                rx,
                ry);


        //如果矩形包含该点 返回真 否则返回假
        return rectF.contains(x, y);

    }

    public void setBaseArea(InchingBaseAreaRelativeLayout rlInchingBaseArea) {
        this.rlInchingBaseArea = rlInchingBaseArea;
    }

    public int getNowPageIndex() {
        return nowPageIndex;
    }

    public void setNowPageIndex(int nowPageIndex) {
        this.nowPageIndex = nowPageIndex;
    }


    public interface UserTouchEventListener {
        void onTouchEvent(MotionEvent event);

        void onMoveOver(NewInchingFrontBoderView broad, int x, int y);
    }


}
